package com.demo.miya.controller;

import com.alibaba.fastjson.JSON;
import com.demo.miya.controller.client.MiyaClient;
import com.demo.miya.model.User;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.TimeUnit;

/**
 * 提供接口给其他项目调用
 * @author K
 */
@Slf4j
@RestController
public class ServiceMiyaController implements MiyaClient {

	@Value("${server.port}")
	private int port;

	/**
	 * luna服务startedController调用
	 * @return 返回结果
	 */
	@Override
	public String hi() {
		log.info("service-miya服务hi接口被调用, port:" + port);
		return "hi i'm miya! port:" + port;
	}

	/**
	 * luna服务startedController调用
	 * 测试aop打印请求url和method日志
	 * @return 返回结果
	 */
	@Override
	public String requestMapping(String param) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		String userId = request.getHeader("userId");
		String userName = request.getHeader("userName");
		log.info("service-miya服务requestMapping接口被调用, 参数：{}, 请求头参数：userId：{}，userName：{}", param, userId, userName);
		return "hi requestMapping!";
	}

	/**
	 * luna服务使用retrofit调用
	 * luna服务使用WebClientService调用
	 * luna服务startedController调用
	 * @param user 请求参数
	 * @return 修改过的User对象
	 */
	@PostMapping("/modifyUser")
	public User modifyUser(@RequestBody User user) {
		user.setUserId(11L);
		user.setUserName("11");
		log.info("修改后user:{}", JSON.toJSONString(user));
		return user;
	}

	/**
	 * luna服务使用WebClientService调用
	 * luna服务startedController通过openfeign调用
	 * @param user 请求参数
	 * @return 返回空对象
	 */
	@PostMapping("/modifyUserException")
	public User modifyUserException(@RequestBody User user) {
		throw new RuntimeException("modifyUserException 接口异常");
	}

	/**
	 * luna服务startedController通过openfeign调用
	 * luna服务MiyaClient通过Http Interface条用
	 * @param timeout 接口等待时间
	 * @return 返回User对象
	 * @throws InterruptedException 线程中断异常
	 */
	@GetMapping("/processLongTime")
	public User processLongTime(@RequestParam("timeout") long timeout) throws InterruptedException {
		TimeUnit.SECONDS.sleep(timeout);
		User user = new User();
		user.setUserId(111L).setUserName("用户名");
		return user;
	}
}
